<template>
  <div>
    <!-- <el-group-title class="d_jump">
      <template slot="groupTitle"> -->
    <el-form
      :model="form"
      ref="form"
      label-width="144px"
      class="ccui-form"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgName">
            <el-select
              v-model="form.reportInOrgName"
              placeholder="请选择填报单位"
              @change="changeReportInOrgId"
            >
              <el-option
                v-for="item in reportOptions"
                :key="item.orgId"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="供应商：" prop="supplierName">
            <el-input
              v-model="form.supplierName"
              placeholder="请输入供应商"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="入库单编号：" prop="storageCode">
            <el-input
              v-model="form.storageCode"
              placeholder="请输入入库单编号"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="入库单名称：" prop="storageName">
            <el-input
              v-model="form.storageName"
              placeholder="请输入入库单名称"
              maxlength="300"
              show-word-limit
              @blur="handleTrim('storageName')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" class="settlementCode">
          <el-form-item label="结算单编号：" prop="settlementCode">
            <!-- <el-row>
                  <el-col> -->
            <el-input
              v-model="form.settlementCode"
              placeholder="请选择结算单编号"
              disabled
            ></el-input>
            <!-- </el-col>
                  <el-col> -->
            <codeNumber
              :reportInOrgId="this.form.reportInOrgId"
              @inventoryConfirm="codeNumberInventoryConfirm"
            ></codeNumber>
            <!-- </el-col>
                </el-row> -->
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="结算单名称：" prop="settlementName">
            <el-input
              v-model="form.settlementName"
              placeholder="请输入结算单名称"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="类型：" prop="finType">
            <el-radio-group v-model="form.finType">
              <el-radio label="0">物资运输</el-radio>
              <el-radio label="1">对下计价</el-radio>
            </el-radio-group>
            <!-- <warehouseDialog
                  @numrow="numrow"
                  :reportInOrgName="form.reportInOrgName"
                /> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" v-if="form.finType == '0'">
        <el-col :span="12" class="flexel">
          <el-form-item label="关联入库单：" prop="refStorageCodeString">
            <el-input
              v-model="form.refStorageCodeString"
              placeholder="请选择关联入库单"
              disabled
            ></el-input>
            <!-- :getTableList="listProtocolinfoPage" -->
          </el-form-item>
          <!-- 关联入库单： -->
          <dialogMultiSelectTable
            :isShow="true"
            btnText="选择"
            dialogTitle="选择"
            :searchInputArr="planSearchInputArr"
            :tableHeadOptions="jsList.planTableHeadOptions"
            :getTableList="listRelationFinStoragePage"
            :optionalParams="optionalParams"
            :selectTableList="relationList"
            @confirm="confirmSelect"
          />
        </el-col>

        <el-col :span="12">
          <el-form-item label="仓库：" prop="warehouseName">
            <el-input
              v-model="form.warehouseName"
              placeholder="请选择仓库"
              disabled
            ></el-input>
            <warehouseDialog
              class="lefeDebug"
              @numrow="numrow"
              :reportInOrgName="form.reportInOrgName"
              :reportInOrgId="form.reportInOrgId"
              :isTrue="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <!-- <el-col :span="12">
              <el-form-item label="物资来源：" prop="materialForm">
                <el-input
                  v-model="form.materialForm"
                  placeholder="请输入物资来源"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col> -->

        <el-col :span="12">
          <el-form-item label="运输产品分类名称：" prop="thirdCategoriesOfName">
            <el-input
              v-model="form.thirdCategoriesOfName"
              placeholder="请输入运输产品分类名称"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="入库数量：" prop="storageCount">
            <el-input
              v-model="form.storageCount"
              placeholder="请输入入库数量"
              @keyup.native="form.storageCount = oninput(form.storageCount)"
              @blur="getblurOne(form.storageCount)"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="入库金额：" prop="storageMoney">
            <el-input
              v-model="form.storageMoney"
              placeholder="请输入入库金额"
              @blur="getblurTow(form.storageMoney)"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="编制人：" prop="reportUsername">
            <el-input
              v-model="form.reportUsername"
              placeholder="请输入编制人"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="编制日期：" prop="reportTime">
            <el-date-picker
              v-model="form.reportTime"
              type="date"
              placeholder="请选择日期"
              format="yyyy-MM-dd"
              disabled
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="入库类型：" prop="storageType">
            <el-select
              v-model="form.storageType"
              class="ccui-form-longInput"
              placeholder="请选择"
              disabled
            >
              <el-option
                v-for="(item, index) in storageTypeList"
                :key="index"
                :label="item.dicValue"
                :value="item.dicKey"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="备注：" prop="remark">
            <el-input
              resize="both"
              type="textarea"
              :rows="5"
              placeholder="请输入备注"
              maxlength="1000"
              show-word-limit
              v-model="form.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- </template>
    </el-group-title> -->
  </div>
</template>

<script>
import { addUrlPerFix } from "@/basa/utils";
import dialogMultiSelectTable from "../../components/dialogMultiSelectTableTow";
import warehouseDialog from "@/app/inventoryManagement/components/warehouseDialog";
import codeNumber from "../../components/codeNumber";
import jsList from "@/app/inventoryManagement/js";
import { getUserInfo, getReportInOrgData } from "@/basa/api";
import {
  getTranWarehousingList,
  listRelationFinStoragePage
} from "../../api/add-item";
import BigNumber from "bignumber.js";
export default {
  components: { dialogMultiSelectTable, codeNumber, warehouseDialog },
  props: {
    storageList: {
      type: Array
    },
    storageForm: {
      type: Object
    },
    tranStorageBObj: {
      type: Object
    },
    associationList: {
      type: Array
    }
  },
  data() {
    return {
      jsList,
      form: {
        finType: "0",
        storageCode: "", //入库单编号
        storageName: "", //入库单名称
        settlementCode: "", //结算单编号
        settlementName: "", //结算单名称
        materialForm: "", //物资来源
        warehouseName: "", //仓库
        storageCount: "", //入库数量
        storageMoney: "", //入库金额
        thirdCategoriesOfName: "", //运输产品分类名称
        thirdCategoriesOfName1: "", //固定存取选择结算单后的物资三级分类名称
        supplierName: "", //供应商名称
        reportInOrgName: "", // 填报单位
        reportUsername: "", // 编制人
        reportTime: "", //编制日期
        remark: "", // 备注
        storageType: "", //入库类型   1，财务入库；0，财务暂估入库
        refStorageCodeString: "", //关联入库单
        refStorageIdString: "", //关联入库单影藏字段
        contractId: 0 //结算单号
      },
      taxNumber: "", // 税率 合同清单 - 计算使用
      rules: {
        storageName: [
          { required: true, message: "请输入入库单名称", trigger: "blur" }
        ],
        settlementCode: [
          { required: true, message: "请选择结算单编号", trigger: "change" }
        ],
        warehouseName: [
          { required: true, message: "请选择仓库", trigger: "change" }
        ],
        reportInOrgName: [
          { required: true, message: "请选择填报单位", trigger: "blur" }
        ],
        finType: [
          { required: true, message: "请选择运输类型", trigger: "change" }
        ],
        refStorageCodeString: [
          { required: true, message: "请选择关联入库单", trigger: "change" }
        ]
      },
      tableData: [],
      storageTypeList: [
        { dicValue: "财务入库", dicKey: 1 },
        { dicValue: "财务暂估入库", dicKey: 0 }
      ],
      reportInOrgObj: {
        title: "填报单位查询",
        tableHeadOptions: jsList.reportInOrgTableHead,
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 20
        }
      },
      reportOptions: [], // 填报单位
      count: 0,
      relationList: [
        // {
        //   id: "00",
        //   flagCurrent: 1,
        //   storageCode: "当期"
        // }
      ],
      optionalParams: {
        storageType: parseInt(this.$route.query.storageType) == 1 ? 1 : 2,
        //contractId: 0,
        reportInOrgId: 0
        //storageStatus: 5
      },
      // 关联入库单 高级搜索 searchInputArr
      planSearchInputArr: [
        { label: "合同名称", value: "contractName" },
        { label: "合同编号", value: "contractCode" },
        { label: "结算单名称", value: "settlementName" },
        { label: "结算单编号", value: "settlementCode" },
        { label: "入库单名称", value: "storageName" },
        { label: "入库单编号", value: "storageCode" },
        { label: "供应商", value: "supplierName" },
        { label: "分类名称", value: "thirdCategoriesOfName" },
        { label: "入库时间", value: "reportTime", type: "date" }
      ]
    };
  },
  watch: {
    $route(to, from) {
      if (to.name == "transport-inventory-financeWarehousing-edit-item") {
        this.addDate(); //获取当前日期
      } else if (from.name == "transport-inventory-financialList-edit-item") {
        this.addDate(); //获取当前日期
      }
    },
    storageForm: {
      handler(newVal, oldVal) {
        if (newVal != {}) {
          this.form.storageCount = this.storageForm.settlementCount;
          this.form.storageMoney = this.storageForm.moneyWithTax;
        }
      },
      deep: true
    },
    "form.finType"(newVal) {
      if (newVal === "1") {
        this.$set(this.form, "thirdCategoriesOfName", "运输服务");
        this.$emit("association", false); //隐藏关联入库单页签
      } else {
        this.$set(
          this.form,
          "thirdCategoriesOfName",
          sessionStorage.getItem("thirdCategoriesOfName")
        );
        this.$emit("association", true); //显示关联入库单页签
      }
    },
    "form.reportInOrgId"(newVal) {
      this.optionalParams.reportInOrgId = newVal;
    },
    associationList(newVal) {
      //关联入库单赋值
      this.relationList = newVal;
    }
  },
  mounted() {
    this.form.storageType =
      sessionStorage.getItem("storageType") == 1 ? "财务入库" : "财务暂估入库";
  },
  created() {
    this.addDate();
  },
  activated() {
    this.getUserInfo();
  },
  methods: {
    confirmSelect(val) {
      console.log("关联入库单", val);
      this.relationList = JSON.parse(JSON.stringify(val));
      let storageCodeArr = [];
      if (val) {
        val.forEach(item => {
          storageCodeArr.push(item.storageCode);

          item.storageCount = item.storageCount
            ? parseFloat(item.storageCount).toFixed(3)
            : "";
          item.storageMoney = item.storageMoney
            ? parseFloat(item.storageMoney).toFixed(2)
            : "";
        });
      }
      this.$set(this.form, "refStorageCodeString", storageCodeArr.join(","));
      this.form.refStorageIdString = storageCodeArr.join(",");
      this.$emit("getAssociationList", val); //入库单数据
    },
    // 选择仓库 返回数据
    numrow(row) {
      this.form.warehouseId = row.id;
      this.form.warehouseCode = row.warehouseCode;
      this.form.warehouseName = row.warehouseName;
    },
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.form.compileUser = res.data.data.userInfo.name;
        this.form.reportUsername = res.data.data.userInfo.name;
        this.userOpenId = res.data.data.userInfo.openId;
        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报信息
    getReportInOrgData(openId) {
      getReportInOrgData({ openIds: [openId] }).then(res => {
        console.log(res.data.data);
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.form.reportInOrgName =
          this.form.reportInOrgName || this.reportOptions[0].name;
        this.form.reportInOrgId =
          this.form.reportInOrgId || this.reportOptions[0].orgId;
      });
    },
    // 填报单位
    changeReportInOrgId(val) {
      const tempObj = this.reportOptions.find(e => e.name === val);
      this.form.reportInOrgId = tempObj.orgId;
      this.form.reportInOrgName = tempObj.name;

      //清空关联入库单信息
      this.$set(this.form, "refStorageCodeString", "");
      this.form.refStorageIdString = "";
      this.$emit("getAssociationList", []); //入库单数据
      this.relationList = [];

      //清空结算单，供应商，采购清单
      this.$set(this.form, "settlementCode", "");
      this.form.settlementName = "";
      this.$set(this.form, "supplierName", "");
      this.$emit("updataList", []);

      //清空仓库
      this.$set(this.form, "warehouseName", "");
      this.form.warehouseId = "";
      this.form.warehouseCode = "";

      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    //结算单编号
    codeNumberInventoryConfirm(data) {
      console.log(data);
      this.form.settlementId = data.id;
      this.form.settlementCode = data.settlementCode;
      this.form.settlementName = data.settlementName;
      this.form.contractId = data.contractId;
      this.form.contractCode = data.contractCode;
      this.form.contractName = data.contractName;
      this.form.supplierName = data.supplierName;
      this.form.supplierId = data.supplierId;
      this.form.supplierCode = data.supplierCode;
      this.count = data.currSetCount;
      this.form.storageCount = data.currSetCount;
      this.form.storageMoney = data.currSetMoney;

      getTranWarehousingList({
        id: data.id,
        storageId: this.tranStorageBObj.id
      }).then(res => {
        console.log(
          "tranStorageListBOList",
          res.data.data.tranStorageListBOList
        );
        this.tableData = new Array();
        res.data.data.tranStorageListBOList.forEach(item => {
          item.materialFirstId = item.materialFirstId || 0;
          item.unStorageCount = item.unStorageCount
            ? item.unStorageCount.toFixed(3)
            : "";
          item.settlementCount = item.settlementCount
            ? item.settlementCount.toFixed(3)
            : "";
          item.count = item.settlementCount;
          item.storageCount = item.settlementCount;
          item.unitPriceWithTax = item.unitPriceWithTax
            ? item.unitPriceWithTax.toFixed(2)
            : "";

          //入库量 不能超过库存
          if (parseFloat(item.storageCount) > parseFloat(item.unStorageCount)) {
            item.storageCount = item.unStorageCount;
          }

          //计算含税金额
          item.moneyWithTax = new BigNumber(
            Number(item.unitPriceWithTax)
          ).multipliedBy(Number(item.storageCount));

          item.moneyWithTax = item.moneyWithTax
            ? item.moneyWithTax.toFixed(2)
            : "";
          let taxRate = new BigNumber(Number(item.taxRate)).plus(1).toString();
          item.moneyWithoutTax = new BigNumber(
            Number(item.moneyWithTax)
          ).dividedBy(taxRate);
          item.moneyWithoutTax = item.moneyWithoutTax
            ? item.moneyWithoutTax.toFixed(2)
            : "";

          this.tableData.push(item);
        });
        //取运输产品分类名称
        if (this.tableData.length > 0) {
          console.log("this.tableData", this.tableData);
          this.$set(
            this.form,
            "thirdCategoriesOfName",
            this.tableData[0].categoryName
          );
          sessionStorage.setItem(
            "thirdCategoriesOfName",
            this.tableData[0].categoryName
          );
          this.form.thirdCategoriesOfName1 = this.tableData[0].categoryName;
        }

        this.$emit("updataList", this.tableData);
      });
    },
    oninput(num) {
      //正则替换
      //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
      var str = num.toString();
      str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
      str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      console.log("input值", str);
      return str;
    },
    getblurOne(declareAmount) {
      this.form.storageCount = this.numberFilter(declareAmount);
    },
    getblurTow(declareAmount) {
      this.form.storageMoney = this.calculateFilter(declareAmount);
    },
    // 金额四舍五入
    calculateFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 9);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 数量四舍五入
    numberFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 4);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    handleSelect() {
      console.log("选择");
      this.$refs["brachFormVisible"].dialogVisible = true;
    },
    //变更策划编码
    planCode(val) {
      console.log(val);
      this.$set(this.form, "planId", val.planId);
      this.$set(this.form, "planCode", val.planCode);
    },
    addDate() {
      let nowDate = new Date();
      console.log(nowDate.getTime());
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      };
      this.form.reportTime = date.year + "-" + date.month + "-" + date.date;
    },
    // input 输入框去掉前后空格
    handleTrim(key) {
      this.$set(this.form, key, this.form[key].replace(/(^\s*)|(\s*)$/g, ""));
    },
    listRelationFinStoragePage
  }
};
</script>

<style scoped lang="scss">
/deep/ .el-input {
  width: 260px;
}

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}
/deep/.ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}
/deep/.lefeDebug {
  margin-left: -6px;
}
/deep/.settlementCode div.el-form-item__content {
  display: flex;
}
//关联入库单按钮
.flexel {
  //display: flex;
  position: relative;
}
.inventory {
  position: absolute;
  top: 0px;
  left: 409px;
}
</style>
